<template>
  <div class="lawfirm-container">
    <el-card class="lawfirm-header">
      <template #header>
        <div class="card-header">
          <h3>律所管理</h3>
          <el-button type="success" @click="handleAdd">+ 新增律所</el-button>
        </div>
      </template>

      <el-form :model="queryForm" ref="queryFormRef" :inline="true" label-width="80px">
        <el-form-item label="关键词">
          <el-input
            v-model="queryForm.keywords"
            placeholder="律所名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="lawfirm-content">
      <el-table
        :data="lawfirmList"
        border
        v-loading="loading"
        class="lawfirm-table"
        :cell-style="cellStyle"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="律所名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="province" label="省份" width="120" show-overflow-tooltip />
        <el-table-column prop="city" label="城市" width="120" show-overflow-tooltip />
        <el-table-column prop="dist" label="区域" width="120" show-overflow-tooltip />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-dropdown @command="handleCommand">
              <el-button size="small">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'edit', row: scope.row }">
                    编辑
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'delete', row: scope.row }" divided>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.limit"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 律所详情抽屉 -->
    <el-drawer
      v-model="detailDrawerVisible"
      :with-header="false"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
      class="lawfirm-drawer"
    >
      <div
        class="drawer-header"
        :class="{
          'add-header': !detailForm.id && !isFormReadOnly,
          'edit-header': detailForm.id && !isFormReadOnly,
          'view-header': isFormReadOnly,
        }"
      >
        <div class="drawer-title">
          <i class="drawer-icon">
            <component :is="isFormReadOnly ? 'View' : detailForm.id ? 'Edit' : 'Plus'" />
          </i>
          {{ drawerTitle }}
        </div>
        <el-icon class="drawer-close" @click="handleDrawerClose"><Close /></el-icon>
      </div>
      <div class="drawer-content">
        <el-form :model="detailForm" :rules="detailRules" ref="detailFormRef" label-width="100px">
          <el-form-item label="律所名称" prop="title">
            <el-input
              v-model="detailForm.title"
              placeholder="请输入律所名称"
              :disabled="isFormReadOnly"
            />
          </el-form-item>
          <el-form-item label="所在地区" required>
            <RegionCascader
              v-model="regionModel"
              emit-path
              placeholder="请选择省/市/区"
              :disabled="isFormReadOnly"
              @change="handleRegionModelChange"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input
              v-model="detailForm.address"
              placeholder="请输入详细地址"
              :disabled="isFormReadOnly"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input
              v-model="detailForm.phone"
              placeholder="请输入联系电话"
              :disabled="isFormReadOnly"
            />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="detailForm.email"
              placeholder="请输入邮箱"
              :disabled="isFormReadOnly"
            />
          </el-form-item>
          <el-form-item label="联系人" prop="contact_person">
            <el-input
              v-model="detailForm.contact_person"
              placeholder="请输入联系人"
              :disabled="isFormReadOnly"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="drawer-footer">
        <template v-if="isFormReadOnly">
          <el-button type="primary" @click="handleDrawerClose" class="close-btn">关闭</el-button>
        </template>
        <template v-else>
          <el-button @click="handleDrawerClose">取消</el-button>
          <el-button
            :type="detailForm.id ? 'warning' : 'success'"
            @click="handleSave"
            :class="{ 'confirm-btn': !detailForm.id, 'edit-btn': detailForm.id }"
          >
            确定
          </el-button>
        </template>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, computed, watch } from 'vue'
  import { getLawfirmList, deleteLawfirm, addLawfirm, editLawfirm } from '@/services/lawyer'
  import { RegionCascader } from '@/components/business/region'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Close, View, Edit, Plus } from '@element-plus/icons-vue'

  const queryForm = reactive({
    page: 1,
    limit: 10,
    keywords: '',
  })

  // 详情表单
  const detailForm = reactive({
    id: 0,
    title: '',
    provinceid: '',
    cityid: '',
    distid: '',
    address: '',
    phone: '',
    email: '',
    contact_person: '',
    status: 1,
  })

  // 表单验证规则
  const detailRules = {
    title: [{ required: true, message: '请输入律所名称', trigger: 'blur' }],
    provinceid: [{ required: true, message: '请选择省份', trigger: 'change' }],
  }

  // 数据相关
  const lawfirmList = ref<any[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 抽屉相关
  const detailDrawerVisible = ref(false)
  const drawerTitle = ref('新增律所')
  // 表单只读状态控制
  const isFormReadOnly = ref(false)

  // 地区模型，用于与RegionCascader组件进行双向绑定
  const regionModel = ref<string>('')

  // 处理地区选择变化
  const handleRegionModelChange = (value: string | string[] | null, selectedOptions: any[]) => {
    console.log('地区选择变化:', value, selectedOptions)
    if (value && selectedOptions && selectedOptions.length > 0) {
      // 从selectedOptions中获取完整的省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      detailForm.provinceid = province?.code || ''
      detailForm.cityid = city?.code || ''
      detailForm.distid = district?.code || ''
    } else if (value) {
      // 如果没有selectedOptions，尝试从value中解析
      if (Array.isArray(value)) {
        // 如果value是数组，取最后一个值作为区县代码
        detailForm.distid = value[value.length - 1]?.toString() || ''
      } else if (typeof value === 'string' && value.includes('/')) {
        // 如果value是完整路径字符串，解析它
        const codes = value.split('/')
        detailForm.provinceid = codes[0] || ''
        detailForm.cityid = codes[1] || ''
        detailForm.distid = codes[2] || ''
      } else {
        // 否则使用value作为区县代码
        detailForm.distid = value?.toString() || ''
      }
    } else {
      detailForm.provinceid = ''
      detailForm.cityid = ''
      detailForm.distid = ''
    }
  }

  // 监听地区模型变化并同步到表单
  watch(
    regionModel,
    newVal => {
      if (newVal) {
        // 新组件返回的是字符串格式，如 "省份代码/城市代码/区县代码"
        const parts = newVal.split('/')
        detailForm.provinceid = parts[0] || ''
        detailForm.cityid = parts[1] || ''
        detailForm.distid = parts[2] || ''
      } else {
        detailForm.provinceid = ''
        detailForm.cityid = ''
        detailForm.distid = ''
      }
    },
    { deep: true }
  )

  // 监听表单地区字段变化并同步到地区模型
  watch(
    () => [detailForm.provinceid, detailForm.cityid, detailForm.distid],
    newVal => {
      const [provinceid, cityid, distid] = newVal
      if (provinceid && cityid && distid) {
        regionModel.value = `${provinceid}/${cityid}/${distid}`
      } else if (provinceid && cityid) {
        regionModel.value = `${provinceid}/${cityid}`
      } else if (provinceid) {
        regionModel.value = provinceid
      } else {
        regionModel.value = ''
      }
    },
    { deep: true }
  )

  // 表单引用
  const detailFormRef = ref()
  const queryFormRef = ref()

  // 查询律所列表
  const loadLawfirmList = async () => {
    loading.value = true
    try {
      const response: any = await getLawfirmList(queryForm)
      if (response.code === 0) {
        lawfirmList.value = response.data.list || []
        total.value = response.data.total || 0
      } else {
        ElMessage.error(response.msg || '获取律所列表失败')
      }
    } catch (error) {
      ElMessage.error('获取律所列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    queryForm.page = 1
    loadLawfirmList()
  }

  // 重置
  const handleReset = () => {
    queryForm.keywords = ''
    queryForm.page = 1
    loadLawfirmList()
  }

  // 添加律所
  const handleAdd = () => {
    drawerTitle.value = '新增律所'
    isFormReadOnly.value = false
    // 重置表单
    Object.assign(detailForm, {
      id: 0,
      title: '',
      provinceid: '',
      cityid: '',
      distid: '',
      address: '',
      phone: '',
      email: '',
      contact_person: '',
      status: 1,
    })
    // 重置地区选择器
    regionModel.value = ''
    detailDrawerVisible.value = true
  }

  // 查看律所详情
  const handleView = (row: any) => {
    drawerTitle.value = '查看律所'
    isFormReadOnly.value = true
    Object.assign(detailForm, row)

    // 从info字段解析数据
    if (row.info) {
      try {
        const info = typeof row.info === 'string' ? JSON.parse(row.info) : row.info
        detailForm.phone = info.phone || ''
        detailForm.email = info.email || ''
        detailForm.contact_person = info.contact_person || ''
      } catch (e) {}
    }

    // 设置地区选择器的值，转换为字符串格式
    const parts = [row.provinceid, row.cityid, row.distid].filter(Boolean)

    regionModel.value = parts.join('/')
    detailDrawerVisible.value = true
  }

  // 编辑律所
  const handleEdit = (row: any) => {
    drawerTitle.value = '编辑律所'
    isFormReadOnly.value = false
    Object.assign(detailForm, row)

    // 从info字段解析数据
    if (row.info) {
      try {
        const info = typeof row.info === 'string' ? JSON.parse(row.info) : row.info
        detailForm.phone = info.phone || ''
        detailForm.email = info.email || ''
        detailForm.contact_person = info.contact_person || ''
      } catch (e) {}
    }

    // 设置地区选择器的值，转换为字符串格式
    const parts = [row.provinceid, row.cityid, row.distid].filter(Boolean)

    regionModel.value = parts.join('/')
    detailDrawerVisible.value = true
  }

  // 修改 addLawfirm 请求参数映射
  const handleSave = async () => {
    if (!detailFormRef.value) return

    await detailFormRef.value.validate(async (valid: boolean) => {
      if (valid) {
        // 额外检查title字段不为空
        if (!detailForm.title || detailForm.title.trim() === '') {
          ElMessage.error('请输入律所名称')
          return
        }

        try {
          // 构造info字段
          const info = {
            phone: detailForm.phone,
            email: detailForm.email,
            contact_person: detailForm.contact_person,
          }

          // 根据是否有id判断是新增还是编辑
          const res = detailForm.id
            ? await editLawfirm({
                id: detailForm.id,
                title: detailForm.title.trim(),
                provinceid: detailForm.provinceid,
                cityid: detailForm.cityid,
                distid: detailForm.distid,
                address: detailForm.address,
                info: JSON.stringify(info),
                status: detailForm.status,
              })
            : await addLawfirm({
                title: detailForm.title.trim(), // 修改 name 为 title 以匹配后端接口
                provinceid: detailForm.provinceid,
                cityid: detailForm.cityid,
                distid: detailForm.distid,
                address: detailForm.address,
                info: JSON.stringify(info),
                status: detailForm.status || 1,
              })
          // @ts-ignore
          if (res.code === 0) {
            ElMessage.success(`${detailForm.id ? '编辑' : '新增'}成功`)
            detailDrawerVisible.value = false
            loadLawfirmList()
          } else {
            // @ts-ignore
            ElMessage.error(res.msg || `${detailForm.id ? '编辑' : '新增'}失败`)
          }
        } catch (error) {
          ElMessage.error(`${detailForm.id ? '编辑' : '新增'}失败`)
        }
      }
    })
  }

  // 删除律所
  const handleDelete = (row: any) => {
    ElMessageBox.confirm(`确定要删除律所【${row.title}】吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await deleteLawfirm(row.id)
          // @ts-ignore
          if (res.code === 0) {
            ElMessage.success('删除成功')
            loadLawfirmList()
          } else {
            // @ts-ignore
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 取消删除
      })
  }

  // 处理命令操作
  const handleCommand = (command: any) => {
    const { action, row } = command
    switch (action) {
      case 'edit':
        handleEdit(row)
        break
      case 'delete':
        handleDelete(row)
        break
    }
  }

  // 抽屉关闭处理
  const handleDrawerClose = () => {
    detailDrawerVisible.value = false
  }

  // 分页变化
  const handlePageChange = (page: number) => {
    queryForm.page = page
    loadLawfirmList()
  }

  // 分页大小变化
  const handleSizeChange = (size: number) => {
    queryForm.limit = size
    queryForm.page = 1
    loadLawfirmList()
  }

  // 表格单元格样式
  const cellStyle = ({ row, column, rowIndex, columnIndex }: any) => {
    // 为地址列添加特殊样式
    if (columnIndex === 5) {
      // 地址列，索引从0开始
      return {
        'white-space': 'nowrap',
        'text-overflow': 'ellipsis',
        overflow: 'hidden',
      }
    }
    return {}
  }

  // 组件挂载时获取数据
  onMounted(() => {
    loadLawfirmList()
  })
</script>

<style scoped>
  .lawfirm-container {
    padding: 20px;
  }

  .lawfirm-header {
    margin-bottom: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
    width: 100%;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  /* 只读表单样式 */
  .el-form-item.is-disabled .el-input__wrapper {
    background-color: #f5f7fa;
    color: #606266;
  }

  /* 表格文字溢出处理 */
  .lawfirm-table .el-table__cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* 表格文字不换行样式 */
  .lawfirm-table .el-table__cell {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /* 抽屉样式 */
  .lawfirm-drawer :deep(.el-drawer__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .drawer-header {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    margin-bottom: 10px;
  }

  .drawer-header.add-header {
    background: linear-gradient(to right, #67c23a, #85ce61, #9adb75);
    color: white;
  }

  .drawer-header.edit-header {
    background: linear-gradient(to right, #e6a23c, #ebb563, #f0c78a);
    color: white;
  }

  .drawer-header.view-header {
    background: linear-gradient(to right, #409eff, #66b1ff, #8cc5ff);
    color: white;
  }

  .drawer-title {
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
  }

  .drawer-title .drawer-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.2);
    margin-right: 8px;
    font-size: 16px;
  }

  .drawer-close {
    cursor: pointer;
    font-size: 20px;
    color: white;
  }

  .drawer-content {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
  }

  .drawer-footer {
    padding: 15px 20px;
    text-align: right;
    border-top: 1px solid #e4e7ed;
    background: #f5f7fa;
  }

  .drawer-footer .confirm-btn {
    background: linear-gradient(to right, #67c23a, #85ce61);
    border-color: #67c23a;
    transition: all 0.3s ease;
  }

  .drawer-footer .edit-btn {
    background: linear-gradient(to right, #e6a23c, #ebb563);
    border-color: #e6a23c;
    transition: all 0.3s ease;
  }

  .drawer-footer .edit-btn:hover {
    background: linear-gradient(to right, #d6962c, #e0a850);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .drawer-footer .confirm-btn:hover {
    background: linear-gradient(to right, #5daf34, #79ba57);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }

  .drawer-footer .close-btn {
    background: linear-gradient(to right, #409eff, #66b1ff);
    border-color: #409eff;
    transition: all 0.3s ease;
  }

  .drawer-footer .close-btn:hover {
    background: linear-gradient(to right, #3a8ee6, #5ca8ff);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  }
</style>
